<?php

namespace App\V3\V3_2_7\Controllers;

use Illuminate\Http\Request;
use App\V3\V3_2_7\Services\CheckStorageManageService;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use App\Helper\Utils\TimeUtil;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\DB;
use App\V3\V3_2_7\Models\CheckStorageManageModel;
use App\V3\V3_2_7\Models\StorageManageModel;
use App\V3\V3_2_7\Models\MaterielTypeModel;
use App\V3\V3_2_7\Models\SerialNumberModel;
use App\V3\V3_2_7\Models\CheckSerialNumberModel;
use App\Services\CommonService;

class CheckStorageManageController extends BaseController
{

    //仓库列表
    public function storageList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|integer',//页面大小
            'currentPage' => 'required|integer',//当前页
        ], [
            'pageSize.required' => '参数`pageSize`丢失',
            'pageSize.integer' => '参数`pageSize`仅能为数字',
            'currentPage.required' => '参数`currentPage`丢失',
            'currentPage.integer' => '参数`currentPage`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        $list = CheckStorageManageService::getStorageList($this->getMainUserId(), $data);
        $this->log('仓库列表', $list);
        return $this->success($list);
    }

    //仓库及商品列表
    public function getStorageGoodsList(Request $request)
    {

        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|integer|min:1',//页面大小
            'currentPage' => 'required|integer',//当前页
        ], [
            'storage_id.required' => '`仓库id`缺失',
            'storage_id.integer' => '`仓库id`只能为数字',
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['main_id'] = $this->getMainUserId();

        $keyword = empty($request->keyword) ? '' : $request->keyword;
        $condition = [];

        if (!empty($request->materiel_class_id)) {

            $data['materiel_class_id'] = $request->materiel_class_id;
        }

        $typeId = [];
        if (!empty($data['type_id'])) {
            $typeId = array_filter(explode(',', $data['type_id']));
        }
        $list = CheckStorageManageService::getStorageGoodsList($request->storage_id, $data, $keyword, $typeId);

        if (!empty($list->toArray())) {
            $list = $list->toArray();
            if (!empty($list['data'])) {
                $res = $list['data'];
                foreach ($res as &$val) {
                    $serialList = [];
                    if (!empty($val['is_use_serial'])) {
                        $serialList = SerialNumberModel::query()
                            ->select(
                                'id as serial_id',
                                'serial_no'
                            )->where([
                                'status' => 1,
                                'delete_flag' => 0,
                                'storage_manage_id' => $val['id'],
                                'goods_id' => $val['type_id'],
                                'main_id' => $data['main_id'],
                            ])->get();

                        if (!empty($serialList->toArray())) {
                            $serialList = $serialList->toArray();
                        }
                    }
                    $val['serial_list'] = $serialList;
                }
                $list['data'] = $res;
            }

        }
        $this->log('仓库及商品列表', $list);
        return $this->success($list);

    }

    public function addCheckStorageGoods(Request $request)
    {

        //参数验证
        $validator = Validator::make($data = $request->all(), [
            /* 'storage_id' => 'required|numeric',*///仓库id
            'sg_type' => [
                'required',
                Rule::In([1, 2])
            ],//盘点类型1:整仓库;2:商品;
        ], [
            /*'storage_id.required'=>'仓库主键`id`缺失',
            'storage_id.numeric' =>'仓库主键`id`必须为整数',*/
            'sg_type.required' => '盘点类型，必要参数',
            'sg_type.in' => '盘点类型:1-整仓库;2-商品;3-自动盘点',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $time = time();
        $this->operateLog('新建整库盘点', $data, $time);
        $arr = array();
        $goodsArr = array();
        $check_no = CommonService::getOrderNo(new CheckStorageManageModel, 'check_no', 'P');
        DB::beginTransaction();
        try {
            if (!empty($data['goods_info'])) {//普通商品
                $goodsInfo = json_decode($data['goods_info'], true);
                foreach ($goodsInfo as $v) {
                    $sInfo = StorageManageModel::select(
                        'b.is_product_materiel',
                        'a.in_storage_num',
                        'b.is_use_serial',
                        'b.materiel_name',
                        'a.storage_id',
                        'a.id'
                    )->from('storage_manage as a')
                        ->leftJoin('materiel_type as b', 'b.id', '=', 'a.type_id')
                        ->where('a.id', $v['storage_manage_id'])
                        ->where('b.id', $v['type_id'])
                        ->where('a.delete_flag', 0)
                        ->where('b.delete_flag', 0)->first()->toArray();

                    if (!empty($sInfo)) {
                        $data['storage_id'] = $sInfo['storage_id'];
                        if (!empty($data['is_cover'])) {//开启序列号
                            if ($sInfo['is_use_serial'] == 1) {
                                //普通商品开启序列号处理
                                if (empty($v['serial_no'])) {
                                    throw new \Exception('商品' . $sInfo['materiel_name'] . '的序列号不能为空');
                                }
                                $serial_no_array = explode(',', $v['serial_no']);
                                if (count($serial_no_array) > $v['check_num']) {
                                    throw new \Exception('序列号数量大于了商品：' . $sInfo['materiel_name'] . '的数量!只需要' . $v['check_num'] . '个序列号');
                                }
                                if (count($serial_no_array) < $v['check_num']) {
                                    throw new \Exception('序列号数量与商品：' . $sInfo['materiel_name'] . '的数量不相等!还差' . $v['check_num'] - $serial_no_array . '个序列号');
                                }
                                foreach ($serial_no_array as $serial_key => $serial_data) {
                                    //检查序列号是否使用
                                    $serialInfo = SerialNumberModel::where([
                                        'goods_id' => $v['type_id'],
                                        'serial_no' => $serial_data,
                                        'delete_flag' => 0
                                    ])->first();

                                    if (empty($serialInfo)) {
                                        SerialNumberModel::insertGetId([
                                            'status' => 1,
                                            'batch_no' => "",
                                            'serial_no' => $serial_data,
                                            'storage_manage_id' => $v['storage_manage_id'],
                                            'goods_id' => $v['type_id'],
                                            'created_at' => $time,
                                            'main_id' => $this->getMainUserId(),
                                        ]);
                                    }
                                }
                                $delSeiralList = SerialNumberModel::select('serial_no')
                                    ->where([
                                        'delete_flag' => 0,
                                        'goods_id' => $v['type_id'],
                                        'storage_manage_id' => $sInfo['id']
                                    ])
                                    ->whereNotIn('serial_no', $serial_no_array)->get()->toArray();

                                $delSeiralData = "";
                                if (!empty($delSeiralList)) {
                                    foreach ($delSeiralList as $dVal) {
                                        $delSeiralData .= $dVal['serial_no'] . ',';
                                    }
                                    $delSeiralData = substr($delSeiralData, 0, strrpos($delSeiralData, ","));

                                    //删除没有选择的序列号
                                    SerialNumberModel::where([
                                        'status' => 1,
                                        'parent_id' => 0,
                                        'storage_manage_id' => $sInfo['id'],
                                        'goods_id' => $v['type_id']
                                    ])->whereNotIn('serial_no', $serial_no_array)->update([
                                        'delete_flag' => 1
                                    ]);
                                }
                                CheckSerialNumberModel::insertGetId([
                                    'status' => 1,
                                    'main_id' => $this->getMainUserId(),
                                    'serial_number' => $v['serial_no'],
                                    'storage_manage_id' => $v['storage_manage_id'],
                                    'type_id' => $v['type_id'],
                                    'product_id' => "",
                                    'del_serial_number' => $delSeiralData,
                                    'goods_flag' => !empty($sInfo['is_product_materiel']) ? 2 : 1,
                                    'check_no' => $check_no,
                                    'created_at' => $time
                                ]);
                            }
                        }
                    } else {
                        throw new \Exception('物料商品的' . $sInfo['materiel_name'] . '不存在');
                    }
                    if (!empty($v['check_num']) && getDecimalPointLeng($v['check_num']) > 7) {
                        throw new \Exception('盘点数小数点后，不能超过6位数字 。');
                    }
                    if (!empty($v['yk_num']) && getDecimalPointLeng($v['yk_num']) > 7) {
                        throw new \Exception('盈亏数量小数点后，不能超过6位数字。');
                    }
                    if (!empty($data['is_cover'])) {
                        $v['is_cover'] = $data['is_cover'];
                    }
                    $v['check_time'] = $time;
                    $v['created_at'] = $time;
                    $v['sg_type'] = $data['sg_type'];
                    $v['user_id'] = $this->getUserId();
                    $v['storage_id'] = $data['storage_id'];
                    $v['main_id'] = $this->getMainUserId();
                    $v['check_no'] = $check_no;
                    $arr[] = [
                        'id' => $v['storage_manage_id'],
                        'in_storage_num' => $v['check_num'],
                        //'virtual_storage_num'=>$v['check_num']
                    ];
                    unset($v['serial_no']);
                    $goodsArr[] = $v;
                }
            }
            if (!empty($data['is_cover'])) {
                if (!empty($arr)) {
                    batch()->update(new StorageManageModel(), $arr, 'id');
                }
            }
            if (!empty($goodsArr)) {
                CheckStorageManageModel::insert($goodsArr);
            }
            CommonService::operateResult($this->getUserId(), $time, $data, '盘点编号：' . $check_no . '创建成功');
            DB::commit();
            return $this->success();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('盘点失败' . var_export($e->getMessage(), true));
            return $this->fail('', $e->getMessage());
        }
    }

    /**
     * 修改仓库和商品盘点数
     * @param check_no 盘点编号
     * @param is_cover 是否开启覆盖库存
     * @param storage_manage_id  库存id
     * @param type_id            物料类型名称/型号id
     * @param yk_flag            物料类型名称/型号id
     * @param check_num  物料类型名称/型号id
     * @param yk_num  物料类型名称/型号id
     */
    public function updCheckStorageGoods(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'check_no' => 'required|integer',//盘点编号
        ], [
            'check_no.required' => '`盘点编号`必要参数',
            'check_no.integer' => '`盘点编号`只能为数字',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $info = CheckStorageManageModel::select('check_no', 'storage_id')
            ->where('check_no', $data['check_no'])->first()->toArray();
        if (empty($info)) return $this->fail('', '没有找到，要修改的盘点数据。');
        $arr = array();
        if (!empty($data['goods_info'])) {
            $goodsInfo = json_decode($data['goods_info'], true);
            DB::beginTransaction();
            try {
                foreach ($goodsInfo as &$v) {
                    if (!empty($v['check_num']) && getDecimalPointLeng($v['check_num']) > 7) {
                        throw new \Exception('盘点数小数点后，不能超过6位。');
                    }
                    if (!empty($v['yk_num']) && getDecimalPointLeng($v['yk_num']) > 7) {
                        throw new \Exception('盈亏数量小数点后，不能超过6位。');
                    }
                    if (!empty($data['is_cover'])) {
                        $v['is_cover'] = $data['is_cover'];
                    }
                    $v['updated_at'] = time();
                    $condition['type_id'] = $v['type_id'];
                    $condition['check_no'] = $info['check_no'];
                    $condition['storage_id'] = $info['storage_id'];
                    $condition['storage_manage_id'] = $v['storage_manage_id'];
                    CheckStorageManageModel::where($condition)->update($v);
                    $arr[] = [
                        'id' => $v['storage_manage_id'],
                        'in_storage_num' => $v['check_num'],
                        //'virtual_storage_num'=>$v['check_num']
                    ];
                }
                if (!empty($data['is_cover'])) {
                    batch()->update(new StorageManageModel(), $arr, 'id');
                }
                $this->log('编辑整库盘点', $data, '盘点编号：' . $data['check_no'] . ',信息已更改！');
                DB::commit();
                return $this->success();
            } catch (\Exception $e) {
                DB::rollBack();
                $this->fail('', $e->getMessage());
            }
        }
    }

    /**
     * 通过批次号查询商品信息（扫一扫）
     * @param Request $request
     */
    public function readBatchNo(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'batch_no' => 'required',//条码信息
            'code_type' => 'required',
        ], [
            'batch_no.required' => '参数`条码信息`缺失',
            'code_type.required' => '参数`码的类型`缺失',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        if (!empty($data['code_type'])) {
            if ($data['code_type'] == 'warehouse') {
                return $this->fail('','无法识别仓库码');
            } elseif ($data['code_type'] == 'location') {
                return $this->fail('','无法识别库位码');
            } elseif ($data['code_type'] == 'shelf') {
                return $this->fail('','无法识别货架码');
            }
        }
        $this->log('通过序列号查询商品信息', $data);
        $data['batch_title'] = $this->batchTitle();
        $data['main_id'] = $this->getMainUserId();
        return response()->json(CheckStorageManageService::readBatchNo($data));
    }

    /**
     * 盘点仓库和商品列表
     * @param Request $request
     */
    public function getCheckList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|integer|min:1',//页面大小
            'currentPage' => 'required|integer',//当前页
        ], [
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        $condition['a.main_id'] = $this->getMainUserId();
        $keyword = empty($request->keyword) ? '' : $request->keyword;
        $list = CheckStorageManageService::checkList($condition, $data, $keyword);
        if (!empty($list['data'])) {
            foreach ($list['data'] as &$val) {
                if (!empty($val['identical_check_goods'])) {
                    foreach ($val['identical_check_goods'] as &$gVal) {
                        $serialInfo = [];
                        if (!empty($gVal['is_cover']) && !empty($gVal['is_use_serial'])) {
                            $serialInfo = CheckSerialNumberModel::select(
                                'serial_number'
                            )->where([
                                'type_id' => $gVal['type_id'],
                                'storage_manage_id' => $gVal['storage_manage_id'],
                                'check_no' => $gVal['check_no'],
                                'delete_flag' => 0
                            ])->first();
                            if (!empty($serialInfo)) {
                                $serialInfo['serial_number'] = explode(',', $serialInfo['serial_number']);
                            }

                            if ($gVal['yk_flag'] == 1) {//盈:把之前加到库存里面扣除
                                $gVal['in_storage_num'] = $gVal['in_storage_num'] - $gVal['yk_num'];
                            } elseif ($gVal['yk_flag'] == 2) {//亏:把之前库存减去的加回来
                                $gVal['in_storage_num'] = $gVal['in_storage_num'] + $gVal['yk_num'];
                            }
                        }
                        $gVal['serial_count'] = !empty($serialInfo['serial_number']) ? count($serialInfo['serial_number']) : 0;
                        $gVal['serial_number'] = $serialInfo['serial_number'] ?? [];
                    }
                }
            }
        }
        return $this->success($list);
    }

    /**
     * 盘点盈亏列表
     * @param Request $request
     */
    public function getCheckYkGoodsList(Request $request)
    {

        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|integer|min:1',//页面大小
            'currentPage' => 'required|integer',//当前页
            'check_no' => 'required',//盘点编号
            /*   'yk_flag' => [
                  'required',
                  Rule::In([1,2])
              ],//盘点类型1:整仓库;2:商品; */
        ], [
            'check_no.required' => '`盘点编号`必要参数',
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
            /*  'yk_flag.required'         =>'盘点类型，必要参数',
             'yk_flag.in'         =>'盘点类型:1、盈;2、亏', */
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        $condition['a.main_id'] = $this->getMainUserId();
        $keyword = empty($request->keyword) ? '' : $request->keyword;
        $list = CheckStorageManageService::checkSkGoodsList($condition, $data, $keyword);

        if (!empty($list['data'])) {
            foreach ($list['data'] as $k => $v) {
                $list['data'][$k]['shelf_name'] = !empty($v['shelf_name']) ? $v['shelf_name'] : "";
                $list['data'][$k]['location_name'] = !empty($v['location_name']) ? $v['location_name'] : "";
                if ($v['is_cover'] == 1) {
                    if ($v['yk_flag'] == 2) {
                        $list['data'][$k]['in_storage_num'] = $v['check_num'] + $v['yk_num'];
                    } elseif ($v['yk_flag'] == 1) {
                        $list['data'][$k]['in_storage_num'] = $v['check_num'] - $v['yk_num'];
                    }
                }
            }
        }
        $this->log('盘点盈亏列表', $list);
        return $this->success($list);
    }

    /**
     * 批量删除盘点数据
     * @param check_no 盘点编号
     */
    public function delCheckStorageData(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'check_no' => 'required',//盘点编号
        ], [
            'check_no.required' => '`盘点编号`必要参数',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return fail('', $info);
        }
        $checkSerialNumber = [];
        $data['check_no'] = explode(',', $data['check_no']);
        if (!empty($data['check_no'])) {
            DB::beginTransaction();
            try {
                CheckStorageManageModel::whereIn('check_no', $data['check_no'])
                    ->update(['delete_flag' => 1]);
                CheckSerialNumberModel::whereIn('check_no', $data['check_no'])
                    ->where(['delete_flag' => 0])
                    ->update(['delete_flag' => 1]);
                $logData = '盘点编号：（' . join(',', $data['check_no']) . '） 记录,已删除！';
                $this->log('批量删除盘点记录', $data, $logData);
                DB::commit();
                return success();
            } catch (\Exception $e) {
                DB::rollBack();
                Log::debug('批量删除盘点记录异常' . var_export($e->getMessage(), true));
                return fail('', $e->getMessage());
            }
        } else {
            return fail('', '请求数据异常');
        }
    }

    public function autoStorageGoodsList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'inventory_code_list' => 'required',//盘点编号
        ], [
            'inventory_code_list.required' => '库存码，不能为空！',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return fail('', $info);
        }
        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();
        $list = CheckStorageManageService::autoStorageGoodsList($data);
        return response()->json(['code' => 0, 'msg' => 'success', 'data' => $list]);
    }

    public function addAutoStorageGoods(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'sg_type' => [
                'required',
                Rule::In([1, 2, 3])
            ],//盘点类型:1-整仓库;2-商品;3-自动盘点
        ], [
            'sg_type.required' => '盘点类型，必要参数',
            'sg_type.in' => '盘点类型:1-整仓库;2-商品;3-自动盘点',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $time = time();
        $this->operateLog('自动盘点', $data, $time);
        $arr = array();
        $goodsArr = array();
        $check_no = CommonService::getOrderNo(new CheckStorageManageModel, 'check_no', 'P');
        DB::beginTransaction();
        try {
            if (!empty($data['goods_info'])) {//普通商品
                $goodsInfo = json_decode($data['goods_info'], true);
                foreach ($goodsInfo as $v) {
                    $sInfo = StorageManageModel::select(
                        'b.is_product_materiel',
                        'a.in_storage_num',
                        'b.is_use_serial',
                        'b.materiel_name',
                        'a.storage_id',
                        'a.id'
                    )->from('storage_manage as a')
                        ->leftJoin('materiel_type as b', 'b.id', '=', 'a.type_id')
                        ->where('a.id', $v['storage_manage_id'])
                        ->where('b.id', $v['type_id'])
                        ->where('a.delete_flag', 0)
                        ->where('b.delete_flag', 0)->first();

                    if (!empty($sInfo)) {
                        $sInfo = $sInfo->toArray();
                        $data['storage_id'] = $sInfo['storage_id'];
                        if (!empty($data['is_cover'])) {
                            //开启序列号
                            if ($sInfo['is_use_serial'] == 1) {
                                //普通商品开启序列号处理
                                if (empty($v['serial_no'])) {
                                    throw new \Exception('商品（' . $sInfo['materiel_name'] . '）的序列号不能为空');
                                }
                                $serial_no_array = explode(',', $v['serial_no']);
                                if (count($serial_no_array) > $v['check_num']) {
                                    throw new \Exception('序列号数量大于了商品（' . $sInfo['materiel_name'] . '）的数量!只需要' . $v['check_num'] . '个序列号');
                                }
                                if (count($serial_no_array) < $v['check_num']) {
                                    throw new \Exception('序列号数量与商品（' . $sInfo['materiel_name'] . '）的数量不相等!还差' . $v['check_num'] - $serial_no_array . '个序列号');
                                }
                                foreach ($serial_no_array as $serial_key => $serial_data) {
                                    //检查序列号是否使用
                                    $serialInfo = SerialNumberModel::where([
                                        'goods_id' => $v['type_id'],
                                        'serial_no' => $serial_data,
                                        'delete_flag' => 0
                                    ])->first();

                                    if (empty($serialInfo)) {
                                        SerialNumberModel::insertGetId([
                                            'status' => 1,
                                            'batch_no' => "",
                                            'serial_no' => $serial_data,
                                            'storage_manage_id' => $v['storage_manage_id'],
                                            'goods_id' => $v['type_id'],
                                            'created_at' => $time,
                                            'main_id' => $this->getMainUserId(),
                                        ]);
                                    }
                                }
                                $delSeiralList = SerialNumberModel::select('serial_no')
                                    ->where([
                                        'delete_flag' => 0,
                                        'goods_id' => $v['type_id'],
                                        'storage_manage_id' => $sInfo['id']
                                    ])
                                    ->whereNotIn('serial_no', $serial_no_array)->get();
                                $delSeiralData = "";
                                if (!empty($delSeiralList->toArray())) {
                                    foreach ($delSeiralList->toArray() as $dVal) {
                                        $delSeiralData .= $dVal['serial_no'] . ',';
                                    }
                                    $delSeiralData = substr($delSeiralData, 0, strrpos($delSeiralData, ","));
                                    //删除没有选择的序列号
                                    SerialNumberModel::where([
                                        'status' => 1,
                                        'parent_id' => 0,
                                        'storage_manage_id' => $sInfo['id'],
                                        'goods_id' => $v['type_id']
                                    ])->whereNotIn('serial_no', $serial_no_array)
                                        ->update([
                                            'delete_flag' => 1
                                        ]);
                                }
                                CheckSerialNumberModel::insertGetId([
                                    'status' => 1,
                                    'main_id' => $this->getMainUserId(),
                                    'serial_number' => $v['serial_no'],
                                    'storage_manage_id' => $v['storage_manage_id'],
                                    'type_id' => $v['type_id'],
                                    'product_id' => "",
                                    'del_serial_number' => $delSeiralData,
                                    'goods_flag' => !empty($sInfo['is_product_materiel']) ? 2 : 1,
                                    'check_no' => $check_no,
                                    'created_at' => $time
                                ]);
                            }
                        }
                    } else {
                        throw new \Exception('自动盘点的商品（' . $sInfo['materiel_name'] . '）不存在');
                    }
                    if (!empty($v['check_num']) && getDecimalPointLeng($v['check_num']) > 7) {
                        throw new \Exception('盘点数小数点后，不能超过6位数字 。');
                    }
                    if (!empty($v['yk_num']) && getDecimalPointLeng($v['yk_num']) > 7) {
                        throw new \Exception('盈亏数量小数点后，不能超过6位数字。');
                    }
                    if (!empty($data['is_cover'])) {
                        $v['is_cover'] = $data['is_cover'];
                    }
                    $v['check_time'] = $time;
                    $v['created_at'] = $time;
                    $v['sg_type'] = 3;
                    $v['user_id'] = $this->getUserId();
                    $v['storage_id'] = $data['storage_id'];
                    $v['main_id'] = $this->getMainUserId();
                    $v['check_no'] = $check_no;
                    $v['check_type'] = $data['check_type'] ?? 0;
                    $arr[] = [
                        'id' => $v['storage_manage_id'],
                        'in_storage_num' => $v['check_num'],
                        //'virtual_storage_num'=>$v['check_num']
                    ];
                    unset($v['serial_no']);
                    $goodsArr[] = $v;
                }
            }
            if (!empty($data['is_cover'])) {
                if (!empty($arr)) {
                    batch()->update(new StorageManageModel(), $arr, 'id');
                }
            }
            if (!empty($goodsArr)) {
                CheckStorageManageModel::insert($goodsArr);
            }
            CommonService::operateResult($this->getUserId(), $time, $data, '盘点编号：' . $check_no . '创建成功');
            DB::commit();
            return $this->success();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('自动盘点异常：' . var_export($e->getMessage(), true));
            return $this->fail('', $e->getMessage());
        }
    }
}
